package cn.ac.ict.debs.testsetGenerator;

import java.io.File;
import java.io.StringWriter;

import javax.xml.parsers.*;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.*;

public class QueryContentGenerator extends Generator
{
	public String getQueryContent(String[] inputs, String[] outputs, boolean saveFile) throws Exception
	{
		for(String s : inputs)
		{
			if(conceptMap.get(s) == null) return null;
		}
		for(String s : outputs)
		{
			if(conceptMap.get(s) == null) return null;
		}
		
		Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(QUERY_T));
		Element[] keyElements = this.getKeyElement(doc);
				
		int id = 100001;
		for(String input : inputs)
		{
			keyElements[0].appendChild(this.createPartElement(doc, id));
			keyElements[2].appendChild(this.createExtElement(doc, id ++, String.format("%d", conceptMap.get(input).getInstId())));
		}
		for(String output : outputs)
		{
			keyElements[1].appendChild(this.createPartElement(doc, id));
			keyElements[3].appendChild(this.createExtElement(doc, id ++, String.format("%d", conceptMap.get(output).getInstId())));
		}
		
		String queryContent = this.doc2String(doc);
		
		if(saveFile)
		{
			this.saveXml(doc, this.DIR + "Challenge.wsdl");
		}
		
		return queryContent;
	}
	
	private Element createExtElement(Document doc, int id, String conceptName)
	{
		Element extElement = doc.createElement("mece:semExt");
		extElement.setAttribute("id", String.format("%d", id));
		
		Element refElement = doc.createElement("mece:ontologyRef");
		refElement.setTextContent("http://www.ws-challenge.org/wsc08.owl#inst" + conceptName);
		extElement.appendChild(refElement);
		
		return extElement;
	}
	
	private Element[] getKeyElement(Document doc)
	{
		Element[] keyElements = new Element[4];
		NodeList list = doc.getDocumentElement().getChildNodes();
		for(int i = 0; i < list.getLength(); i ++)
		{
			Node child = list.item(i);
			if(!(child instanceof Element)) continue;
			Element childElement = (Element)child;
			if(childElement.getTagName().equals("message"))
			{
				if(childElement.getAttribute("name").equals("Task0RequestMessage"))
				{
					keyElements[0] = childElement;
				}
				else
				{
					keyElements[1] = childElement;
				}
			}
			else if(childElement.getTagName().equals("mece:semExtension"))
			{
				NodeList semList = childElement.getChildNodes();
				for(int j = 0; j < semList.getLength(); j ++)
				{
					Node semChild = semList.item(j);
					if(!(semChild instanceof Element)) continue;
					Element semChildElement = (Element)semChild;
					if(semChildElement.getAttribute("id").equals("Task0RequestMessage"))
					{
						keyElements[2] = semChildElement;
					}
					else
					{
						keyElements[3] = semChildElement;
					}
				}
			}
		}
		return keyElements;
	}
	
	private Element createPartElement(Document doc, int id) // <part element="service:232866887" name="232866887Part" />
	{
		Element partElement = doc.createElement("part");
		partElement.setAttribute("element", String.format("service:%d", id));
		partElement.setAttribute("name",    String.format("%dPart", id));
		return partElement;
	}
	
	private String doc2String(Document document) 
    { 
      String s = ""; 
      try 
       {    
           Transformer transformer = TransformerFactory.newInstance().newTransformer();                     
           StringWriter out = new StringWriter();  
           transformer.transform(new DOMSource( document ), new StreamResult(out)); 
           out.flush(); 
           s = out.toString(); 
       }
      catch(Exception ex) 
       {             
           ex.printStackTrace(); 
       }       
      return s; 
    }
}
